const initialState = {
  commentData: {} as CommentDataType,
  originComment: {} as CommentItemType,
  replyData: {} as CommentDataType,
};

export type ActionType =
  | { type: 'comment/saveComment'; payload: CommentDataType }
  | { type: 'comment/clearComent' }
  | { type: 'comment/saveOrigin'; payload: CommentItemType }
  | { type: 'comment/updateComment'; payload: CommentItemType }
  | { type: 'comment/likeComment'; payload: string }
  | { type: 'comment/saveReply'; payload: CommentDataType };

function commentReducer(state = initialState, action: ActionType): typeof initialState {
  switch (action.type) {
    case 'comment/saveComment':
      return {
        ...state,
        commentData: {
          ...action.payload,
          results: [...(state.commentData.results || []), ...action.payload.results],
        },
      };

    case 'comment/clearComent': {
      return { ...state, commentData: {} as CommentDataType };
    }

    case 'comment/saveOrigin': {
      return { ...state, originComment: action.payload };
    }
    case 'comment/updateComment':
      return {
        ...state,
        commentData: {
          ...state.commentData,
          total_count: state.commentData.total_count + 1,
          results: [action.payload, ...state.commentData.results],
        },
      };

    case 'comment/likeComment':
      const oldCommentList = state.commentData.results;
      const newList = [...oldCommentList];
      const findItem = newList.find((item) => item.com_id === action.payload);
      findItem!.like_count += findItem?.is_liking ? -1 : 1;
      findItem!.is_liking = !findItem!.is_liking;

      return {
        ...state,
        commentData: {
          ...state.commentData,
          results: newList,
        },
      };

    case 'comment/saveReply':
      return {
        ...state,
        replyData: action.payload,
      };

    default:
      return state;
  }
}

export default commentReducer;

interface CommentDataType {
  total_count: number;
  end_id: string;
  last_id: string;
  results: CommentItemType[];
}

export interface CommentItemType {
  com_id: string;
  content: string;
  reply_count: number;
  pubdate: string;
  is_followed: boolean;
  is_liking: boolean;
  like_count: number;
  aut_id: string;
  aut_name: string;
  aut_photo: string;
}
